﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.JScript;

using Kaixin001.Common;
using KxzzEntity.UsersEntity;
using Entity.MsgEntity;
using Kaixin001.StringUtil;


namespace Kaixin001.Msg
{
    public class MsgHelper
    {
        #region 变量
        private string baseUrl = "http://www.kaixin001.com";
        private string msgBaseUrl = "http://www.kaixin001.com/msg/";
        private string msgInboxUrl = "http://www.kaixin001.com/msg/inbox.php";
        private string msgGbookUrl = "http://www.kaixin001.com/comment/uindex.php?t=";
        private string msgPlUrl = "http://www.kaixin001.com/comment/?t=";
        private string msgSysUrl = "http://www.kaixin001.com/msg/sys.php?t=";
        private string msgGbookReplyUrl = "http://www.kaixin001.com/comment/usend.php?t=";
        private string msgPlReplyUrl = "http://www.kaixin001.com/comment/send.php?t=";
        private string msgPostUrl = "http://www.kaixin001.com/msg/post.php";
        private string msgReplyUrl = "http://www.kaixin001.com/msg/reply.php";

        private string rcode = string.Empty;
        private double r;
        private Random ran = new Random(System.Convert.ToInt32(DateTime.Now.Second));
        Kaixin001Http kaixin001Http;
        #endregion
        
        #region 属性
        /// <summary>
        /// 获取t
        /// </summary>
        public double RandomCode
        {
            get
            {
                return Microsoft.JScript.MathObject.ceil(this.ran.NextDouble() * 100);
            }
        }
        #endregion

        #region 构造函数
        public MsgHelper(Kaixin001Http kaixin001Http)
        {
            this.kaixin001Http = kaixin001Http;
        }
        #endregion

        /// <summary>
        /// 更新用户消息条数
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserInfoEntity GetMsgCount(UserInfoEntity user)
        {
            WebResponse webResponse = kaixin001Http.doGetRetry(this.msgBaseUrl);

            string resultHtml = this.kaixin001Http.GetHtml(webResponse);

            if (resultHtml.Contains("消息中心 - 开心网"))
            {
                //匹配短消息数量
                Regex regex = new Regex("id=body_msg_num>(?<count>\\d{1,9})条新</a>");
                MatchCollection matchs = regex.Matches(resultHtml);

                matchs = regex.Matches(resultHtml);
                user.MessageCount = int.Parse(matchs[0].Groups["count"].Value);

                //匹配系统消息数量
                regex = new Regex("id=body_sysmsg_num>(?<count>\\d{1,9})条新</a>");
                matchs = regex.Matches(resultHtml);
                user.SysMessageCount = int.Parse(matchs[0].Groups["count"].Value); ;

                //匹配留言数量
                regex = new Regex("id=body_bbs_num>(?<count>\\d{1,9})条新</a>");
                matchs = regex.Matches(resultHtml);
                user.GuestBookCount = int.Parse(matchs[0].Groups["count"].Value);

                //匹配评论数量
                regex = new Regex("id=body_reply_num>(?<count>\\d{1,9})条新");
                matchs = regex.Matches(resultHtml);
                user.CommentCount = int.Parse(matchs[0].Groups["count"].Value);

            }
            return user;
        }

        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public List<MessageGroupEntity> GetAllMessage(UserInfoEntity user)
        {
            List<MessageGroupEntity> mge = new List<MessageGroupEntity>();
            MessageGroupEntity messageGroupEntity = new MessageGroupEntity();

            this.rcode = this.RandomCode.ToString();
            string resultHtml = "";
            string strNowPage = "";
            bool blnHasNextPage = false;
            string strUrl = string.Format(this.msgInboxUrl + "?t={0}", this.rcode);
            strNowPage = strUrl;
            GotoNextPage:
            if (blnHasNextPage)
            {
                messageGroupEntity = new MessageGroupEntity();
                strUrl =strNowPage;
            }

            Regex regex =  new Regex("href=\"(?<messageUrl>.+)\"\\s+title=\"查看该消息\">");
            //regex = new Regex("unread.gif(?s)(?i)<div><a\\s+class=\"sl\"\\s+(?<messageUrl>.+)查看该消息");
            MatchCollection matchs = regex.Matches(resultHtml);

            resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(strUrl));
            matchs = regex.Matches(resultHtml);

            //分离出对话N组
            #region 获取当前页面所有信息
            foreach (Match match in matchs)
            {
                MatchCollection matchInner = null;
                messageGroupEntity = new MessageGroupEntity();

                messageGroupEntity.ThreadUrl = this.baseUrl + match.Groups["messageUrl"].Value;

                #region 获取对话的用户
                regex = new Regex("style=\"margin-top:50px;margin-left:15px;\">(?<FromUser>.+)和(?<ToUser>.+)之间的私密对话</b></div>");
                resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(messageGroupEntity.ThreadUrl));
                matchInner = regex.Matches(resultHtml);
                if (matchInner.Count > 0)
                {
                    string strFromUser = matchInner[0].Groups["FromUser"].Value;
                    string strToUser = matchInner[0].Groups["ToUser"].Value;
                    regex = new Regex("<a\\s+href=\"/home/\\?uid=(?<uid>\\d+)\"\\s+class=\"sl\"\\s+title=\"(?<userName>.+)\">");
                    matchInner = regex.Matches(strFromUser);
                    if (matchInner.Count > 0)
                    {
                        messageGroupEntity.Uid = matchInner[0].Groups["uid"].Value;
                        messageGroupEntity.FriendName = matchInner[0].Groups["userName"].Value;
                    }
                    else
                    {
                        matchInner = regex.Matches(strToUser);
                        if (matchInner.Count > 0)
                        {
                            messageGroupEntity.Uid = matchInner[0].Groups["uid"].Value;
                            messageGroupEntity.FriendName = matchInner[0].Groups["userName"].Value;
                        }
                    }
                }
                #endregion

                resultHtml = StringHelper.GetMidString(resultHtml, "之间的私密对话", "<div class=\"dxx_sc\">");
                regex = new Regex("<div\\s+class=\"dxx4\"><div\\s+class=\"l50_s\">(?<innerHtml>[\\s\\S]*)<div\\s+class=\"c\"></div>");
  
                matchInner = regex.Matches(resultHtml);

                if (matchInner.Count == 1)
                {
                    resultHtml = matchInner[0].Groups["innerHtml"].Value;

                    #region 获取对话内容

                    string[] strHtml = Regex.Split(resultHtml, "<div class=\"dxx4\"><div class=\"l50_s\">", RegexOptions.IgnoreCase);
                    foreach (string str in strHtml)
                    {
                        MessageEntity messageEntity = new MessageEntity();

                        regex = new Regex("<a\\s+href=\"/home/\\?uid=(?<uid>\\d+)\"\\s+class=\"sl\".+>(?<user>.+)</a>");
                        matchInner = regex.Matches(str);
                        if (matchInner.Count > 0)
                        {
                            messageEntity.SendUid = matchInner[0].Groups["uid"].Value;
                            messageEntity.SendUser = matchInner[0].Groups["user"].Value;

                            if (messageEntity.SendUid == user.Uid)
                            {
                                messageEntity.FromUser = user.Name;
                                messageEntity.ToUser = messageGroupEntity.FriendName;
                            }
                            else
                            {
                                messageEntity.FromUser = messageEntity.SendUser;
                                messageEntity.ToUser = user.Name;
                            }
                        }

                        regex = new Regex("</a><br /><span class=\"c9\">(?<time>.+)</span>");
                        matchInner = regex.Matches(str);
                        if (matchInner.Count > 0)
                            messageEntity.SendTime = matchInner[0].Groups["time"].Value;

                        string strMessage = StringHelper.GetMidString(str, "<div class=\"dxx_mr4\" style=\"width:570px;\">", "</div>");
                        if (!string.IsNullOrEmpty(strMessage))
                            messageEntity.Message = strMessage;

                        if (!string.IsNullOrEmpty(StringHelper.DelHtmlString(messageEntity.Message)))
                        {
                            messageGroupEntity.MessageList.Add(messageEntity);
                        }
                    }
                    #endregion
                }
                mge.Add(messageGroupEntity);
            }
            #endregion


            regex = new Regex("<a href=\"\\?start=(?<start>\\d+)\"\\s+class=fy\\s+onfocus=\".+\">下一页");
            resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(strNowPage));
            matchs = regex.Matches(resultHtml);
            if (matchs.Count > 0)
            {
                strNowPage = this.msgInboxUrl + "?start=" + matchs[0].Groups["start"].Value;
                blnHasNextPage = true;
            }
            else
            {
                blnHasNextPage = false;
            }
            if (blnHasNextPage)
            {
                goto GotoNextPage;
            }
            return mge;
        }

        /// <summary>
        /// 获取新消息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public List<MessageGroupEntity> GetNewMessage(UserInfoEntity user)
        {
            List<MessageGroupEntity> mge = new List<MessageGroupEntity>();
            MessageGroupEntity messageGroupEntity = new MessageGroupEntity();

            this.rcode = this.RandomCode.ToString();
            string resultHtml = "";
            string strUrl = string.Format(this.msgInboxUrl + "?t={0}", this.rcode);

            resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(strUrl));

            if (resultHtml.Contains("<div class=\"dxx_of\" id=\"message1\" onmouseover=\"msgOnmouseover(1)\" onmouseout=\"msgOnmouseout(1)\" />"))
            {
                StringBuilder sbStart = new StringBuilder();
                sbStart.Append("<div class=\"dxx_of\" id=\"message1\" onmouseover=\"msgOnmouseover(1)\" onmouseout=\"msgOnmouseout(1)\" />");

                resultHtml = StringHelper.GetMidString(resultHtml, sbStart.ToString(), "<div id=\"rightinfo\" style=\"display:block;\">");
                string[] strThreadMids = Regex.Split(resultHtml,
                    "<div\\s+class=\"dxx_of\"\\s+id=\"message\\d+\"\\s+onmouseover=\"msgOnmouseover\\(\\d+\\)\"\\s+onmouseout=\"msgOnmouseout\\(\\d+\\)\"\\s+/>",
                     RegexOptions.IgnoreCase);

                foreach (string strThreadMid in strThreadMids)
                {
                    if (strThreadMid.Contains("unread.gif"))
                    {
                        Regex regex = new Regex("href=\"(?<messageUrl>.+)\"\\s+title=\"查看该消息\">");
                        MatchCollection match = regex.Matches(strThreadMid);
                        if (match.Count > 0)
                        {
                            MatchCollection matchInner = null;
                            messageGroupEntity = new MessageGroupEntity();

                            messageGroupEntity.ThreadUrl = this.baseUrl + match[0].Groups["messageUrl"].Value;

                            #region 获取对话的用户
                            regex = new Regex("style=\"margin-top:50px;margin-left:15px;\">(?<FromUser>.+)和(?<ToUser>.+)之间的私密对话</b></div>");
                            resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(messageGroupEntity.ThreadUrl));
                            matchInner = regex.Matches(resultHtml);
                            if (matchInner.Count > 0)
                            {
                                string strFromUser = matchInner[0].Groups["FromUser"].Value;
                                string strToUser = matchInner[0].Groups["ToUser"].Value;
                                regex = new Regex("<a\\s+href=\"/home/\\?uid=(?<uid>\\d+)\"\\s+class=\"sl\"\\s+title=\"(?<userName>.+)\">");
                                matchInner = regex.Matches(strFromUser);
                                if (matchInner.Count > 0)
                                {
                                    messageGroupEntity.Uid = matchInner[0].Groups["uid"].Value;
                                    messageGroupEntity.FriendName = matchInner[0].Groups["userName"].Value;
                                }
                                else
                                {
                                    matchInner = regex.Matches(strToUser);
                                    if (matchInner.Count > 0)
                                    {
                                        messageGroupEntity.Uid = matchInner[0].Groups["uid"].Value;
                                        messageGroupEntity.FriendName = matchInner[0].Groups["userName"].Value;
                                    }
                                }
                            }
                            #endregion

                            resultHtml = StringHelper.GetMidString(resultHtml, "之间的私密对话", "<div class=\"dxx_sc\">");
                            #region 获取对话内容

                            string[] strHtml = Regex.Split(resultHtml, "<div class=\"dxx4\"><div class=\"l50_s\">", RegexOptions.IgnoreCase);
                            foreach (string str in strHtml)
                            {
                                MessageEntity messageEntity = new MessageEntity();

                                regex = new Regex("<a\\s+href=\"/home/\\?uid=(?<uid>\\d+)\"\\s+class=\"sl\".+>(?<user>.+)</a>");
                                matchInner = regex.Matches(str);
                                if (matchInner.Count > 0)
                                {
                                    messageEntity.SendUid = matchInner[0].Groups["uid"].Value;
                                    messageEntity.SendUser = matchInner[0].Groups["user"].Value;

                                    if (messageEntity.SendUid == user.Uid)
                                    {
                                        messageEntity.FromUser = user.Name;
                                        messageEntity.ToUser = messageGroupEntity.FriendName;
                                    }
                                    else
                                    {
                                        messageEntity.FromUser = messageEntity.SendUser;
                                        messageEntity.ToUser = user.Name;
                                    }
                                }

                                regex = new Regex("</a><br /><span class=\"c9\">(?<time>.+)</span>");
                                matchInner = regex.Matches(str);
                                if (matchInner.Count > 0)
                                    messageEntity.SendTime = matchInner[0].Groups["time"].Value;

                                regex = new Regex("<div\\s+class=\"dxx_mr4\"\\s+style=\"width:570px;\">(?<message>[\\s\\S]+)</div>[\\s\\S]+<div class=\"c\"></div>");
                                matchInner = regex.Matches(str);
                                if (matchInner.Count > 0)
                                {
                                    messageEntity.Message = matchInner[0].Groups["message"].Value.TrimStart(new char[] { '\r', '\t', '\n' }).TrimEnd(new char[] { '\r', '\t', '\n' });
                                    messageEntity.Message = Regex.Replace(messageEntity.Message, "<img.+?(\\d+)\\.gif\"[^>]*>(\\w*)", "{$$" + "${1}" + "}" + "${2}");

                                }

                                if (!string.IsNullOrEmpty(messageEntity.Message))
                                {
                                    messageEntity.Message = StringHelper.DelHtmlString(messageEntity.Message);
                                    messageGroupEntity.MessageList.Add(messageEntity);
                                }
                            }
                            #endregion
                            mge.Add(messageGroupEntity);
                        }
                    }
                }
            }
            return mge;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="uids"></param>
        /// <param name="message"></param>
        /// <param name="textType"></param>
        /// <returns></returns>
        public bool SendMessage(string uids, string message, string textType)
        {
            bool result = false;
            this.rcode = this.RandomCode.ToString();

            string postData = string.Format("attachment_random=&attachment_cancel=&uids={0}&rcode={1}&content={2}&texttype={3}&code=",
                uids,
                this.rcode,
                GlobalObject.encodeURIComponent(message),
                textType);

            WebResponse webResponse = this.kaixin001Http.doPost(msgPostUrl, postData);

            if (webResponse != null && webResponse.ResponseUri.AbsolutePath == @"/msg/send.php")
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 回复消息
        /// </summary>
        /// <param name="threadMid"></param>
        /// <param name="uids"></param>
        /// <param name="message"></param>
        /// <param name="textType"></param>
        /// <returns></returns>
        public bool ReplyMessage(string threadMid,string uids, string message, string textType)
        {
            bool result = false;

            string postData = string.Format("attachment_random=&attachment_cancel=&uids={0}uc=1&thread_mid={1}&content={2}&texttype={3}code=",
                uids,
                threadMid,
                GlobalObject.encodeURIComponent(message),
                textType);

            WebResponse webResponse = this.kaixin001Http.doPost(msgReplyUrl, postData);

            if (webResponse != null && webResponse.ResponseUri.ToString() == this.msgReplyUrl)
            {
                result = true;
            }

            return result;
        }
    }
}
